namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Globalization;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Globalization;
    using SimpleWebServices.Net.Mail;
    using SimpleWebServices.Web;
    using SimpleWebServices.Web.Routing;

    [InternalServerError]
    [Allow(Methods = "GET, HEAD, OPTIONS")]
    [CacheControl, ContentLanguage, ContentMD5]
    public sealed class NotFoundController : Controller, IRegisterRoutes
    {
        void IRegisterRoutes.Register(RouteCollection routes)
        {
            if (null == routes)
            {
                throw new ArgumentNullException("routes");
            }

            routes.MapRoute(
                "GET {*url}",
                "{*url}",
                new { controller = "NotFound", action = "HtmlRepresentation" },
                new { method = new HttpMethodConstraint("GET") });

            routes.MapRoute(
                "HEAD {*url}",
                "{*url}",
                new { controller = "NotFound", action = "HtmlRepresentation" },
                new { method = new HttpMethodConstraint("HEAD") });
        }

        public ActionResult HtmlRepresentation()
        {
            new CultureInfo("en").SetCurrentCulture();

            HttpContextFactory.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;

            NotFound model = new Default().Object<NotFound>().ApplyDefaultValues<NotFound>();
            model.Cacheability = HttpCacheability.NoCache;

            new NotFoundMailMessage(this.ControllerContext).Send();

            return View(model);
        }
    }
}